#! /bin/bash

# 获取环境变量
PLAY_HOME=/opt/playground
# 获取版本参数
DOCKER_VERSION=$1

function configureDocker()
{
# 更换国内镜像源
cat >> /etc/docker/daemon.json << EOF
{
  "registry-mirrors": [
    "https://registry.docker-cn.com",
    "http://hub-mirror.c.163.com",
    "https://dockerhub.azk8s.cn",
    "https://mirror.ccs.tencentyun.com",
    "https://registry.cn-hangzhou.aliyuncs.com",
    "https://docker.mirrors.ustc.edu.cn",
    "https://docker.m.daocloud.io",   
    "https://noohub.ru", 
    "https://huecker.io",
    "https://dockerhub.timeweb.cloud" 
  ]
}
EOF
systemctl restart docker
}

function installDocker()
{
 #1.在frames.txt中查看是否需要安装docker
 dockerInfo=`egrep "^docker" $PLAY_HOME/frames.txt`

 docker=`echo $dockerInfo | cut -d " " -f1`
 isInstall=`echo $dockerInfo | cut -d " " -f2`
 dockerNodes=`echo $dockerInfo | cut -d " " -f3` 
 node=`hostname`

 #是否安装
 if [[ $isInstall = "true" && $dockerNodes =~ $node ]];then
    
     #2.查看$PLAY_HOME/frames目录下是否有docker安装脚本
     dockerIsExists=`find $PLAY_HOME/frames -name "get-docker.sh"`

     if [[ ${#dockerIsExists} -ne 0 ]];then

          chmod +x $PLAY_HOME/frames/get-docker.sh
          
          # 根据版本参数安装不同版本
          if [[ "$DOCKER_VERSION" == "26.1.4" ]]; then
              echo "正在安装 Docker 26.1.4 版本..."
              sh $PLAY_HOME/frames/get-docker.sh --mirror Aliyun --version 26.1.4
          else
              echo "正在安装 Docker 最新版本..."
              sh $PLAY_HOME/frames/get-docker.sh --mirror Aliyun
          fi
          
          systemctl start docker
          systemctl enable docker
     else
         echo "$PLAY_HOME/frames目录下没有get-docker安装脚本"
         echo "开始下载get-docker.sh脚本"
         curl -fsSL https://get.docker.com -o $PLAY_HOME/frames/get-docker.sh
         chmod +x $PLAY_HOME/frames/get-docker.sh
         echo "下载成功，开始安装"
         
         # 根据版本参数安装不同版本
         if [[ "$DOCKER_VERSION" == "26.1.4" ]]; then
             echo "正在安装 Docker 26.1.4 版本..."
             sh $PLAY_HOME/frames/get-docker.sh --mirror Aliyun --version 26.1.4
         else
             echo "正在安装 Docker 最新版本..."
             sh $PLAY_HOME/frames/get-docker.sh --mirror Aliyun
         fi
         
         systemctl start docker
         systemctl enable docker
     fi
     configureDocker
 else
     echo "Docker不允许安装在当前节点，请检查配置文件！"
 fi

}

installDocker
